﻿using DLL.Models;
using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace DLL.Repository
{
    public class JobRepository : IJobRepository
    {
        private readonly AppDbContext _db;

        public JobRepository(AppDbContext db)
        {
            _db = db;
        }

        public async Task Create(JobPosition item)
        {
            var entry = _db.Entry(item);
            if (entry.State == EntityState.Detached)
                _db.JobPositions.Add(item);
            await _db.SaveChangesAsync();
        }

        public async Task Delete(JobPosition item)
        {
            var result = await GetById(item.Id);
            if (result != null)
            {
                _db.JobPositions.Remove(item);
                await _db.SaveChangesAsync();
            }
        }

        public async Task<IEnumerable<JobPosition>> GetAll()
        {
            return await _db.JobPositions
               .ToListAsync();
        }

        public async Task<JobPosition> GetById(int id)
        {
            return await _db.JobPositions
                .FirstOrDefaultAsync(i => i.Id == id);
        }

        public async Task Update(JobPosition item)
        {
            var result = await GetById(item.Id);
            if (result != null)
            {
                _db.JobPositions.Update(item);
                await _db.SaveChangesAsync();
            }
        }
    }
}
